<template>
  <el-dialog
    v-model="visible"
    :title="userId ? '编辑用户' : '新增用户'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!userId">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="部门" prop="dept_id">
        <el-select v-model="form.dept_id" placeholder="请选择部门" clearable filterable style="width: 100%">
          <el-option
            v-for="dept in departments"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="最大设备数" prop="max_devices">
        <el-input-number 
          v-model="form.max_devices" 
          :min="1" 
          :max="5" 
          placeholder="请输入最大设备数"
          style="width: 100%"
        />
        <div style="color: #909399; font-size: 12px; margin-top: 5px;">
          允许该用户同时登录的设备数量，范围：1-5，默认：1
        </div>
      </el-form-item>
      <el-form-item label="角色" prop="role_ids">
        <el-select v-model="form.role_ids" multiple placeholder="请选择角色" style="width: 100%">
          <el-option
            v-for="role in roles"
            :key="role.id"
            :label="role.name"
            :value="role.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  userId: {
    type: Number,
    default: null,
  },
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const roles = ref([])
const departments = ref([])

const form = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  password: '',
  dept_id: null,
  status: 1,
  max_devices: 1,
  role_ids: [],
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' },
  ],
  nickname: [
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  max_devices: [
    { required: true, message: '请输入最大设备数', trigger: 'blur' },
    { type: 'number', min: 1, max: 5, message: '最大设备数范围：1-5', trigger: 'blur' },
  ],
  password: [
    { 
      required: true, 
      message: '请输入密码', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (!props.userId && !value) {
          callback(new Error('请输入密码'))
        } else if (value && value.length < 6) {
          callback(new Error('密码长度不能小于6位'))
        } else {
          callback()
        }
      }
    },
  ],
}

watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    Promise.all([fetchRoles(), fetchDepartments()])
    if (props.userId) {
      fetchUser()
    } else {
      resetForm()
    }
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

const fetchRoles = async () => {
  try {
    const response = await request.get('/roles/all/list')
    if (response.code === 200) {
      roles.value = response.data
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

const fetchDepartments = async () => {
  try {
    const response = await request.get('/departments', {
      params: { tree: true, status: 1 },
    })
    if (response.code === 200) {
      // 扁平化部门树
      const flattenDepts = (depts) => {
        let result = []
        depts.forEach(dept => {
          result.push({ id: dept.id, name: dept.name })
          if (dept.children && dept.children.length > 0) {
            result = result.concat(flattenDepts(dept.children))
          }
        })
        return result
      }
      departments.value = flattenDepts(response.data)
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
  }
}

const fetchUser = async () => {
  try {
    const response = await request.get(`/users/${props.userId}`)
    if (response.code === 200) {
      Object.assign(form, {
        username: response.data.username,
        nickname: response.data.nickname,
        email: response.data.email,
        phone: response.data.phone,
        dept_id: response.data.dept_id || null,
        status: response.data.status,
        max_devices: response.data.max_devices || 1,
        role_ids: response.data.roles?.map(r => r.id) || [],
      })
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const resetForm = () => {
  Object.assign(form, {
    username: '',
    nickname: '',
    email: '',
    phone: '',
    password: '',
    dept_id: null,
    status: 1,
    max_devices: 1,
    role_ids: [],
  })
  formRef.value?.clearValidate()
}

const handleClose = () => {
  visible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const url = props.userId ? `/users/${props.userId}` : '/users'
        const method = props.userId ? 'put' : 'post'
        const data = { ...form }
        if (props.userId && !data.password) {
          delete data.password
        }
        const response = await request[method](url, data)
        if (response.code === 200) {
          ElMessage.success(props.userId ? '更新成功' : '创建成功')
          emit('success')
        }
      } catch (error) {
        console.error('保存用户失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

